<template>
  <el-drawer size="514" class="jzt-drawer" v-model="_isOpen" :title="isOld() ? '修改合同' : '新增合同'" @close="cancelClick">
    <el-form v-loading="loadingFlag" ref="formRef" :model="form" label-width="auto" label-position="top" :rules="rules">
      <el-form-item label="合同模板" prop="templateId">
        <el-select :disabled="isOld()" v-model="form.templateId" placeholder="请选择合同模板" @change="changeTemp">
          <el-option
            v-for="item in contractTempList"
            :key="item.templateId"
            :label="item.templateName"
            :value="item.templateId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="合同编码" v-if="isOld()" prop="contractNo">
        <el-input disabled v-model="form.contractNo" />
      </el-form-item>
      <el-form-item label="合同名称" prop="title">
        <el-input v-model="form.title" />
      </el-form-item>
      <el-form-item label="合同类型" prop="contractTypeId">
        <el-select disabled v-model="form.contractTypeId" placeholder="请选择合同类型">
          <el-option
            v-for="item in contractTypeList"
            :key="item.contractTypeId"
            :label="item.contractTypeName"
            :value="item.contractTypeId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="签约方式" prop="signingMethod">
        <el-select :disabled="signDisabled" v-model="form.signingMethod" placeholder="请选择签约方式">
          <el-option
            v-for="item in signingMethodList"
            :key="item.signingMethod"
            :label="item.signingMethodName"
            :value="item.signingMethod"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        label="客户身份证号"
        prop="customerIdCard"
        v-if="contractTempList.find(item => form.templateId === item.templateId)?.existIdNumber && form.signingMethod === 2"
      >
        <el-input v-model="form.customerIdCard" />
      </el-form-item>
      <el-form-item label="客户信息" prop="customer">
        <el-input disabled v-model="form.customer" />
      </el-form-item>
      <el-form-item label="合同总金额" prop="totalAmount">
        <el-input disabled v-model="form.totalAmount">
          <template #suffix>元</template>
        </el-input>
      </el-form-item>
      <el-form-item label="合同创建日期" prop="contractDate">
        <el-date-picker
          :disabled="!isOld()"
          v-model="form.contractDate"
          style="width: 100%"
          type="date"
          placeholder="请选择日期"
        />
      </el-form-item>
      <div>
        <div>合同工期</div>
        <div class="content-card">
          <el-form-item
            label-position="left"
            label="房屋面积"
            prop="area"
            :rules="{
              required: true,
              type: 'number',
              message: '请输入房屋面积',
              trigger: 'change'
            }"
          >
            <el-input v-model.number="form.area" placeholder="请输入房屋面积" @change="handleArea" type="number" :min="0">
              <template #append>㎡</template>
            </el-input>
          </el-form-item>
          <el-form-item label-position="left" label="其他场景" prop="otherDurationIds">
            <el-select v-model="form.otherDurationIds" placeholder="请选择" multiple>
              <el-option
                :label="item.otherName"
                :value="item.durationOtherId"
                v-for="item in buildConfig.otherVOList"
                :key="item.durationOtherId"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label-position="left"
            label="施工日"
            prop="workType"
            :rules="{
              required: true,
              message: '请选择施工日',
              trigger: 'change'
            }"
          >
            <el-radio-group v-model="form.workType">
              <el-radio :value="2">自然日</el-radio>
              <el-radio :value="1">工作日</el-radio>
            </el-radio-group>
          </el-form-item>
          <div class="content-num">
            <div class="content-num-title">经计算合同工期：{{ form.contractDuration > 0 ? form.contractDuration : "--" }}天</div>
            <div class="content-num-list" v-show="otherData.length > 0 || day">
              <div class="mb10 list-item" v-show="day">标准天数：{{ day || 0 }}天</div>
              <div class="mb10 list-item" v-for="item in otherData" :key="item.durationOtherId">
                {{ item.otherName }}：{{ item.otherType === 1 ? "+" : "-" }}{{ item.otherDates }}天
              </div>
            </div>
          </div>
        </div>
      </div>
      <el-form-item label="合同订单号" prop="budgetTemplateId">
        <el-input disabled v-model="form.budgetTemplateId" />
      </el-form-item>
      <el-form-item label="预算报价单" prop="budgetName">
        <el-input disabled v-model="form.budgetName" />
      </el-form-item>
      <div class="dialog-footer" style="display: flex; justify-content: center">
        <el-button type="info" @click="cancelClick" class="space_param_btn" style="background: #f2f3f5; color: black">
          取消
        </el-button>
        <el-button type="primary" @click="confirmClick" class="space_param_btn" style="background: #424e66"> 保存合同 </el-button>
      </div>
    </el-form>
  </el-drawer>
</template>
<script setup>
import { computed, defineEmits, ref, watch } from "vue";
import { getBuildConfig, getContractDetail, getContractList, getContractTypeList } from "@/apis/quote-price/following";

const buildConfig = ref({
  otherVOList: [],
  detailVOList: []
});
const day = ref();
const props = defineProps({
  modelValue: () => false,
  budgetDetail: { type: Object, default: () => ({}) },
  customDetail: { type: Object, default: () => ({}) },
  tempDetail: { type: Object, default: () => ({}) },
  contractType: { type: String, default: () => "" }
});

const isOld = () => {
  return form.value.contractId && form.value.status !== 4;
};

const _isOpen = computed(() => {
  return props.modelValue;
});

const emit = defineEmits(["update:modelValue", "cancel", "submit"]);

const otherData = computed(() => {
  if (form.value.otherDurationIds?.length > 0) {
    return buildConfig.value.otherVOList?.length > 0
      ? buildConfig.value.otherVOList.filter(item =>
          form.value.otherDurationIds.some(mustItem => mustItem === item.durationOtherId)
        )
      : [];
  } else {
    return [];
  }
});
const formRef = ref();
const form = ref({
  internalDuration: "",
  contractDuration: "",
  otherDurationIds: "",
  contractId: props.budgetDetail.contractId,
  templateId: "",
  title: "",
  contractTypeId: props.budgetDetail.contractType || props.contractType, // 本身就绑定了||纯采购后期手动绑定
  customer: `${props.customDetail.customerName} / ${props.customDetail.customerMobileCode} / ${props.customDetail.customerAddress}`,
  customerId: props.customDetail.customerId,
  customerName: props.customDetail.customerName,
  customerMobileCode: props.customDetail.customerMobileCode,
  customerAddress: props.customDetail.customerAddress,
  signingMethod: null,
  totalAmount:
    props.budgetDetail.concludeMoney === "" || props.budgetDetail.concludeMoney === null
      ? props.budgetDetail.budgetTotlalMoney
      : props.budgetDetail.concludeMoney,
  contractDate: new Date(),
  budgetTemplateId: props.tempDetail.templateId,
  budgetId: props.budgetDetail.budgetId,
  budgetName: props.budgetDetail.budgetName
});
const signDisabled = ref(false);
const loadingFlag = ref(false);

const contractTempList = ref([]);
const contractTypeList = ref([]);
const signingMethodList = ref([
  { signingMethodName: "纸质", signingMethod: 1 },
  { signingMethodName: "电子", signingMethod: 2 }
]);

const changeTemp = val => {
  const obj = contractTempList.value.find(item => item.templateId === val);
  form.value.title = obj.templateName || "";
};
const gerBuild = async () => {
  const { data } = await getBuildConfig(form.value.customerId);
  buildConfig.value = data;
  if (!isOld()) {
    form.value.area = data.area || "";
  }
};
(async () => {
  loadingFlag.value = true;
  if (form.value.contractId) {
    console.log(form.value.contractId);
    let { data } = await getContractDetail(form.value.contractId);
    form.value = { ...form.value, ...data };
  }
  await gerBuild();
  await handleArea(form.value.area);
  contractTempList.value = (await getContractList(form.value.contractTypeId)).data || [];
  contractTypeList.value = (await getContractTypeList()).data || [];
  const contractType = contractTypeList.value?.find(item => item.contractTypeId === form.value.contractTypeId);
  if (contractType?.signingMethod !== 3) {
    signDisabled.value = true;
    form.value.signingMethod = contractType?.signingMethod;
  }
  loadingFlag.value = false;
})();

const cancelClick = () => {
  emit("update:modelValue", false);
};

const confirmClick = async () => {
  await formRef.value.validate((valid, fields) => {
    if (valid) {
      emit("submit", form.value);
    } else {
      console.log("error submit!", fields);
    }
  });
};

const rules = ref({
  templateId: [{ required: true, message: "请输入合同标题", trigger: "blur" }],
  title: [{ required: true, message: "请输入合同标题", trigger: "blur" }],
  contractDate: [{ required: true, message: "请选择合同创建日期", trigger: "blur" }],
  signingMethod: [{ required: true, message: "请选择签约方式", trigger: "blur" }],
  customerIdCard: [{ required: true, message: "请选输入用户身份证", trigger: "blur" }]
});
// 输入面积
const handleArea = async value => {
  console.log(value);
  if (value) {
    let len = buildConfig.value.detailVOList?.length;
    let detailVOList = buildConfig.value.detailVOList;
    if (detailVOList.length <= 0) {
      day.value = buildConfig.value.internalDuration;
      form.value.internalDuration = buildConfig.value.internalDuration;
      return;
    }
    for (let i = 0; i < detailVOList.length; i++) {
      if (i !== len - 1) {
        if (value <= detailVOList[i].durationVal) {
          form.value.internalDuration = detailVOList[i].internalDuration;
          day.value = detailVOList[i].contractDuration;
          break;
        }
      } else {
        if (value >= detailVOList[i].durationVal) {
          form.value.internalDuration = detailVOList[i].internalDuration;
          day.value = detailVOList[i].contractDuration;
          break;
        }
      }
    }
  } else {
    form.value.internalDuration = "";
    day.value = "";
  }
};

watch([() => otherData.value, () => day.value], newVal => {
  console.log(newVal, 88888);
  let sum = 0;
  if (newVal[0].length > 0) {
    newVal[0].forEach(item => {
      if (item.otherType === 1) {
        sum += item.otherDates;
      } else {
        sum -= item.otherDates;
      }
    });
  }
  form.value.contractDuration = sum + newVal[1] || "";
});
</script>
<style lang="scss" scoped>
.form_box {
  padding: 0 20px;

  .el-form-item__label {
    color: #86909c;
  }
}

.content-card {
  margin-top: 10px;
  margin-bottom: 20px;
  padding: 10px 20px;
  border-radius: 4px 4px 4px 4px;
  border: 1px solid #e1e6ed;
}

.content-num {
  padding: 10px 14px;
  background: #f5f7fa;

  &-title {
    font-size: 14px;
    color: #3d3d3d;
  }

  &-list {
    margin-top: 10px;
    font-size: 12px;
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;

    .list-item {
      width: 30%;
      color: #86909c;
    }
  }

  &-list:after {
    content: "";
    width: 30%;
  }
}

.mb10 {
  margin-bottom: 10px;
}

:deep(.el-input-group__append) {
  background: #f2f3f5 !important;
}
</style>
